package thread.state;

public class ThreadJoinTest {
    public static void main(String[] args) {
        CustomThread0 thread0 = new CustomThread0();
        CustomThread1 thread1 = new CustomThread1();

        thread0.setThreadToBeJoined(thread1);
        thread1.setThreadToJoin(thread0);

        thread0.start();
        thread1.start();
    }
}

class CustomThread0 extends Thread {
    public Thread mThreadToBeJoined;

    @Override
    public void run() {
        super.run();

        System.out.println("Thread " + Thread.currentThread().getName() + " start()");

        long startTime = System.currentTimeMillis();

        while ((System.currentTimeMillis() - startTime) <= 3000) {
            // do nothing
        }

        System.out.println("Thread " + mThreadToBeJoined.getName() + " state = " + mThreadToBeJoined.getState().toString());

        System.out.println("Thread " + Thread.currentThread().getName() + " end()");
    }

    public void setThreadToBeJoined(Thread threadToBeJoined) {
        mThreadToBeJoined = threadToBeJoined;
    }
}

class CustomThread1 extends Thread {
    Thread mThreadToJoin;

    @Override
    public void run() {
        System.out.println("Thread " + Thread.currentThread().getName() + " start()");

        super.run();

        long startTime = System.currentTimeMillis();

        while ((System.currentTimeMillis() - startTime) <= 2000) {
            // do nothing
            try {
                mThreadToJoin.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("Thread " + Thread.currentThread().getName() + " end()");
    }

    public void setThreadToJoin(Thread threadToJoin) {
        mThreadToJoin = threadToJoin;
    }
}
